package com.chery.media.ui.main

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.chery.media.contacts.EventContacts
import com.chery.media.databinding.ActivityMainBinding
import com.chery.media.helper.BluetoothHelper
import com.chery.media.helper.LocationHelper
import com.chery.media.library.adapter.FragmentAdapter
import com.chery.media.library.base.BaseVMActivity
import com.chery.media.library.extend.explainPermissions
import com.chery.media.library.extend.statusBarTransparentLight
import com.chery.media.library.extend.toJson
import com.chery.media.library.extend.toast
import com.chery.media.network.model.AppInfoBean
import com.chery.media.ui.main.app.AppListFragment
import com.chery.media.ui.main.home.HomeFragment
import com.chery.media.ui.music.MusicFloatWindow
import com.chery.media.ui.music.musicViewModel
import com.chery.media.utils.StorageManagerUtils
import com.jeremyliao.liveeventbus.LiveEventBus

class MainActivity : BaseVMActivity<MainViewModel, ActivityMainBinding>() {


    private lateinit var fragmentAdapter: FragmentAdapter

    @SuppressLint("WrongConstant")
    override fun initView(savedInstanceState: Bundle?) {
        statusBarTransparentLight()
        setCallBack()
        viewModel.getAllLauncherIconPackages(this)
        PermissionUtils.permission(*PermissionUtils.getPermissions().toTypedArray())
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(granted: MutableList<String>) {

                }

                override fun onDenied(
                    forever: MutableList<String>, denied: MutableList<String>
                ) {

                }

            })
            .request()
        LocationHelper.getNowLocation(this)
    }
    override fun initObserve() {
        LiveEventBus.get<Unit>(EventContacts.SWITCH_LANGUAGE).observe(this) {
            LogUtils.e("切换语言==============")
        }
    }

    override fun onResume() {
        super.onResume()
        MusicFloatWindow.dismissMusic()
    }

    override fun initData() {
        viewModel.appInstallList.observe(this) {
//            LogUtils.e("切换语言==============${it.toJson()}")
            val fragments = mutableListOf<Fragment>()
            val homeInstallApp = arrayListOf<AppInfoBean>()
            it.forEachIndexed { index, appInfo ->
                if (index < 8) {
                    homeInstallApp.add(appInfo)
                }
            }
            fragments.add(HomeFragment.newInstance(homeInstallApp))
            it.removeAll(homeInstallApp.toSet())
            val totalCount = if (it.size % 18 > 0) it.size / 18 + 1 else it.size / 18
            LogUtils.eTag("总页数=====", "$totalCount")
            val apps = getPageData(it, totalCount)
            for (index in 0 until totalCount) {
                val appList = arrayListOf<AppInfoBean>()
                for (app in apps[index]) {
                    appList.add(app)
                }
                fragments.add(AppListFragment.newInstance(appList))
            }
            fragmentAdapter = FragmentAdapter(supportFragmentManager, fragments)
            mBinding.viewPager.setScroll(true)
            mBinding.viewPager.adapter = fragmentAdapter
            mBinding.viewPager.offscreenPageLimit = fragments.size - 1
        }
    }

    private fun getPageData(apps: ArrayList<AppInfoBean> , pageNum: Int): MutableList<MutableList<AppInfoBean>> =
        mutableListOf<MutableList<AppInfoBean>>().apply {
            for (index in 0 until pageNum) {
                add(apps.subList(index * 18, (index * 18 + 18).coerceAtMost(apps.size)))
            }
        }

    var exitTime = 0L

    private fun setCallBack() {
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
//                if (System.currentTimeMillis() - exitTime > 2000) {
//                    "再按一次退出".toast()
//                    exitTime = System.currentTimeMillis()
//                } else {
//                    AppUtils.exitApp()
//                }
            }
        })
    }

}
